package com.cn.learn.httpclient.service.impl;

import com.cn.learn.httpclient.domain.vo.ResultVO;
import com.cn.learn.httpclient.service.ISendRequestService;
import com.cn.learn.httpclient.util.ServletUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.IOException;

/**
 * @ClassName SendRequestServiceImpl
 * @Description 发送请求服务层实现类
 * @Author JiJiang
 * @Date 2023/5/20 15:45
 * @Version 1.0
 */

@Service
public class SendRequestServiceImpl implements ISendRequestService {


    @Resource
    private PoolingHttpClientConnectionManager httpClientManager;


    @Override
    public ResultVO<Object> getRequest() {

        CloseableHttpResponse response = null;
        try {
            //1.获取请求参数
            Object testParam = ServletUtil.getParam("testParam");

            //2.从连接池中获取HttpClient对象
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(httpClientManager).build();

            //3.创建HttpGet请求并进行相关设置
            HttpGet httpGet = new HttpGet("http://www.itcast.cn/?username=java");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.50");
            //5.发起请求
            response = httpClient.execute(httpGet);
            //6.判断响应状态码并获取响应数据
            if (response.getStatusLine().getStatusCode() == 200) {//200表示响应成功
                String html = EntityUtils.toString(response.getEntity(), "UTF-8");
                return ResultVO.getResult(html);
            }

        } catch (Exception e) {
            System.out.println("getRequest执行异常");
        } finally {
            if (response != null) {
                //7.关闭资源
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return ResultVO.getResult(null);
    }
}
